<template>
  <Form ref="formCom" :validation-schema="mySchems" autocomplete="off" v-slot="{errors}" class="xtx-form">
    <div class="user-info" >
      <img :src="avater" />
      <p>Hi，{{nickname}} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{err:errors.mobile}" v-model="form.mobile" name="mobile" class="input" type="text" placeholder="绑定的手机号" />
      </div>
      <div class="error" v-if="errors.mobile">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{err:errors.code}" v-model="form.code" name="code" class="input" type="text" placeholder="短信验证码" />
        <span class="code" @click="send">
          {{ time === 0 ? "发送验证码" : `${time}秒后重发` }}
        </span>
      </div>
      <div class="error" v-if="errors.code">{{errors.code}}</div>
    </div>
    <a href="javascript:;" @click="submit" class="submit">立即绑定</a>
  </Form>
</template>

<script>
import qc from 'qc'
import { reactive, ref, onUnmounted } from 'vue'
import { Form, Field } from 'vee-validate'
import schems from '@/utils/vee-validate-schema'
import { useIntervalFn } from '@vueuse/core'
import Message from '@/components/library/Message'
import { userQQBandCode, userQQBindLogin } from '@/api/user'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  components: { Form, Field },
  setup (props) {
    const nickname = ref(null)
    const avater = ref(null)
    const formCom = ref(null)
    const time = ref(0)
    const store = useStore()
    const router = useRouter()
    // 获取头像及昵称
    if (qc.Login.check()) {
      qc.api('get_user_info').success(res => {
        nickname.value = res.data.nickname
        avater.value = res.data.figureurl_1
      })
    }
    // 表单数据对象
    const form = reactive({
      mobile: '',
      code: ''
    })
    const mySchems = {
      mobile: schems.mobile,
      code: schems.code
    }
    // 发送验证码
    const send = async () => {
      const valid = mySchems.mobile(form.mobile)
      if (valid === true) {
        if (time.value === 0) {
          await userQQBandCode(form.mobile)
          Message({ text: '验证码发送成功' })
          form.code = 123456
          time.value = 60
          resume()
        }
      } else {
        formCom.value.setFieldError('mobile', valid)
      }
    }
    // 验证码倒计时
    const { pause, resume } = useIntervalFn(
      () => { time.value--; if (time.value === 0) pause() },
      1000,
      false
    )

    // 立即绑定
    const submit = () => {
      const valid = formCom.value.validate() // 校验整个表单
      if (valid) {
        debugger
        userQQBindLogin({ unionId: props.unionId, ...form }).then(data => {
          const { id, nickname, avatar, token, mobile } = data.result
          store.commit('user/setUser', { id, nickname, avatar, token, mobile })
          store.dispatch('cart/margeCart').then(() => {
            router.push(store.state.user.redirectUrl || '/') // 路由回转
            Message({ text: '登录成功！' })
          })
        }).catch(e => {
          Message({ type: 'error', text: '账号绑定失败！' })
        })
      }
    }

    onUnmounted(() => { pause() })
    return { nickname, avater, form, mySchems, send, formCom, time, submit }
  }
}
</script>

<style scoped lang='less'>
.user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    width: 80px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
</style>
